﻿namespace Snipps.Infrastructure.Behaviors
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Interactivity;

    public class ScreollIntoViewBehavior : Behavior<ListView>
    {
        protected override void OnAttached()
        {
            AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged;
            AssociatedObject.Loaded += AssociatedObject_Loaded;
            AssociatedObject.SizeChanged += AssociatedObject_SizeChanged;
        }

        private void AssociatedObject_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            ScrollToView(sender);
        }

        private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            ScrollToView(sender);
        }

        protected override void OnDetaching()
        {
            AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged;
            AssociatedObject.Loaded -= AssociatedObject_Loaded;
            AssociatedObject.SizeChanged -= AssociatedObject_SizeChanged;
        }

        private void ScrollToView(object sender)
        {
            var listView = sender as ListView;
            if (listView != null)
            {
                if (listView.SelectedItem != null)
                {
                    listView.ScrollToCenterOfView(listView.SelectedItem);
                }
            }
        }

        private void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ScrollToView(sender);
        }
    }
}